package garagesession;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.TimeZone;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sourceforge.jgrib.GribFile;
import net.sourceforge.jgrib.GribRecordLight;
import net.sourceforge.jgrib.NoValidGribException;
import net.sourceforge.jgrib.NotSupportedException;

/**
 * Servlet implementation class TestjGRIB
 */
public class TestjGRIB extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * Default constructor. 
	 */
	public TestjGRIB() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * Merge of the <code>doGet</code> and <code>doPost</code> methods.
	 */
	public void doRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		// Get UTC TimeZone
		TimeZone tz = TimeZone.getTimeZone("GMT + 0");
		TimeZone.setDefault(tz);

		long startTime = Calendar.getInstance().getTimeInMillis();

		try {
			System.out.println("coucou");
			StringBuilder sb = new StringBuilder();

			// Create GribFile instance
			File f = new File("/home/moos/Dev/apache-tomcat-6.0.26/webapps/TestjGRIB/samples/21062010_1200.grb");
			if (f == null){System.err.println("pwaaat");}
			GribFile gribFile = new GribFile("/home/moos/Dev/apache-tomcat-6.0.26/webapps/TestjGRIB/samples/21062010_1200.grb");

			if (gribFile != null) {
				GribRecordLight tGrl[] = gribFile.getLightRecords();
				if (tGrl != null) {
					for (int i = 0; i < tGrl.length; i++) {
						sb.append(tGrl[i].toString() + "\n");
					}
				} else {
					sb.append("tGrl is null!");
				}
			}
			else{
				sb.append("gribFile is null");
			}
			// Goodbye message
			long processTime = Calendar.getInstance().getTimeInMillis() - startTime;
			sb.append("Processed in " + processTime + "ms");
			request.setAttribute("gribRecordLights", sb.toString());

		} catch (FileNotFoundException fnfe) {
			System.err.println("FileNotFoundException : " + fnfe);
		} catch (IOException ioe) {
			System.err.println("IOException : " + ioe);
		} catch (NoValidGribException nvge) {
			System.err.println("NoValidGribException : " + nvge);
		} catch (NotSupportedException nse) {
			System.err.println("NotSupportedException : " + nse);
		}

		request.getRequestDispatcher("/index.jsp").forward(request, response);
	}

	/**
	 * see doRequest method
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doRequest(request, response);
	}

	/**
	 * see doRequest method
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doRequest(request, response);
	}

}
